package a01_数组;

import java.util.Arrays;

/**
 * <p>
 * a03_有序数组的平方
 * </p>
 *
 * @author flyduck
 * @since 2024-06-12
 */
public class a04_有序数组的平方复习3 {

    public static void main(String[] args) {
        int[] nums = {-4,-1,0,3,10};
        int[] result = sortedSquares(nums);
        System.out.println("result = " + Arrays.toString(result));
    }


    public static int[] sortedSquares(int[] nums) {
        int[] newArray = new int[nums.length];
        int newIndex = newArray.length - 1;

        int leftIndex = 0;
        int rightIndex = nums.length - 1;

        while (leftIndex <= rightIndex) {
            if(nums[leftIndex] * nums[leftIndex] >= nums[rightIndex] * nums[rightIndex]){
                newArray[newIndex] = nums[leftIndex] * nums[leftIndex];
                leftIndex++;
            }else {
                newArray[newIndex] = nums[rightIndex] * nums[rightIndex];
                rightIndex--;
            }
            newIndex--;
        }
        return newArray;
    }
}
